package com.ai.bitcoin.interceptor;

import com.ai.bitcoin.common.trace.TraceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.DispatcherType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class CommonHandlerInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler)
            throws Exception {
        if (request.getDispatcherType().equals(DispatcherType.ASYNC)) {
            log.info("preHandle ASYNC requestURI:{}", request.getRequestURI());
            TraceUtil.setTraceId((String) request.getAttribute(TraceUtil.TRACE_ID));
            return true;
        } else {
            log.info("preHandle SYNC requestURI:{}", request.getRequestURI());
            return preHandleSync(request, response, handler);
        }
    }

    public boolean preHandleSync(HttpServletRequest request,
                                 HttpServletResponse response, Object handler)
            throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        request.setAttribute(TraceUtil.TRACE_ID, TraceUtil.getTraceId());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception arg3)
            throws Exception {
        log.debug("afterCompletion traceId:{}", request.getAttribute(TraceUtil.TRACE_ID));
        long startTime = (Long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        long executeTime = endTime - startTime;
        log.info("afterCompletion,完整请求耗时:{}ms", executeTime);
    }
}

